package com.example.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xuanyang on 2018/3/13.
 */

public class MyService extends Service {

    private boolean isAppStart = false;// 判断软件是否打开，过滤重复执行
    private String packageName_now = "";//记录当前所在应用的包名

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        timer.schedule(task, 0, 500); //开始监听应用，每500毫秒查询一次
        super.onCreate();


        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    Handler handler_listen = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
//                ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//                ComponentName cn = am.getRunningTasks(1).get(0).topActivity;//获取到栈顶最顶层的activity所对应的应用
//                String packageName = cn.getPackageName();//从ComponentName对象中获取到最顶层的应用包名
//                String packageName = ForegroundAppUtil.getForegroundActivityName(MyService.this);
                String packageName = Utils.getTopStackPkg(MyService.this);
                if (!packageName_now.equals(packageName)) {//如果两个包名不相同，那么代表切换了应用
                    packageName_now = packageName;//更新当前的应用包名
                    Log.i(Constants.LogTag, packageName);
                }

            }
            super.handleMessage(msg);
        }

        ;
    };

    Timer timer = new Timer();
    TimerTask task = new TimerTask() {

        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler_listen.sendMessage(message);
        }
    };

    @Override
    public void onDestroy() {
        timer.cancel();//销毁服务的时候同时关闭定时器timer
        super.onDestroy();
    }

}
